<template>
    <div class="orderListRuleForm">
        <panle title='制作海报' content="制作海报"></panle>
        <el-button class="create_poster" type="primary" size="mini" @click="createdPoster">创建</el-button>
        <!--搜索-->
        <el-form :inline="true" ref="form" :model="form" label-width="100px" class="demo-form-inline">
            <el-form-item label="海报名称:" prop="title">
                <el-input size="mini" placeholder="请输入" v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search" size="mini">搜索</el-button>
                <el-button @click="resetForm('form')" size="mini">重置</el-button>
                <el-button size="mini" @click="init()">刷新</el-button>
            </el-form-item>
        </el-form>
        <!--列表-->
        <div class="table-wrap">
            <el-table :data="tableData" v-loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all>
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="content" label="海报内容">
                    <template slot-scope="scope">
                        <el-image :src="scope.row.content" fit="fill" style="width: 60px;height: 60px;"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="海报名称"></el-table-column>
                <el-table-column prop="goods_name" label="商品名称"></el-table-column>
                <el-table-column prop="id" label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" label="下载" icon="fa  fa-pencil" @click="uploadPoster(scope.row)">下载</el-button>
                        <el-button type="text" size="mini" label="编辑" icon="fa  fa-pencil" @click="editPoster(scope.row,2)">编辑</el-button>
                        <el-button type="text" size="mini" label="删除" icon="fa  fa-pencil" @click="delPoster(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @size-change="handlePostersSizeChange" @current-change="handlePostersCurrentChange"
                               :current-page="form.pagePostersNumber" :page-sizes="[10, 50, 100, 200]"
                               :page-size="form.pagePostersSize"
                               background layout="total, sizes, prev, pager, next, jumper"
                               :total="form.postersTotal">
                </el-pagination>
            </div>
        </div>
        <!--添加/编辑-->
        <el-dialog :visible.sync="PosterOpen" width="1000px" :before-close="handleClose" append-to-body :title="!posterForm.id ? '创建海报' : '编辑海报'">
            <el-form ref="posterForm" :model="posterForm" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="添加背景" prop="basemap">
                            <div class="uploadcol" v-if="dialogImageUrl">
                                <draggable
                                    handle=".mover"
                                    @end="onEnd($event)"

                                    :style="{ width: '100%', height: 'auto' }"
                                >
                                  <div v-if="popuQrcode" style="position: relative;width: 100%;height: 100%">
                                    <img draggable= "true" class="qrCode mover" :style="{ left: position.x + 'px', top: position.y + 'px' }" ref="qRcodeImage" :src="popuQrcode" :width="qr_w" :height="qr_h" />
                                  </div>
<!--                                    <div draggable= "true"  v-if="popuQrcode" class="qrCode mover" :style="{ left: position.x + 'px', top: position.y + 'px' }">-->
<!--                                        <img ref="qRcodeImage" :src="popuQrcode" width="150" height="150" />-->
<!--                                    </div>-->
                                </draggable>
                                <div class="uploadimgborder">
                                    <img ref="dialogImage" v-if="dialogImageUrl" :src="dialogImageUrl" width="375" />
                                    <img v-else src="@/assets/img/uploadimg.jpg" width="30%" height="30%" />
                                </div>

                            </div>
                            <el-button type="primary" @click="openUploadDialBg" size="mini" style="margin-top:10px">上传模板</el-button>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="添加推广链接：" prop="popu_link_id">
                            <el-button type="primary" size="mini" @click="selectPopuLink">添加推广链接</el-button>
                        </el-form-item>
                        <el-table :data="selectPopuItem" style="width: 100%;margin-bottom: 20px;" border stripe default-expand-all v-if="currentPopuShow == true">
                            <el-table-column prop="name" label="商品名称"></el-table-column>
                            <el-table-column prop="img" label="缩略图">
                                <template slot-scope="scope">
                                    <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
                                </template>
                            </el-table-column>
                            <el-table-column prop="goods_quantity" label="商品数量"></el-table-column>
                            <el-table-column prop="sold_quantity" label="已售数量"></el-table-column>
                            <el-table-column prop="link_price" label="商品价格（单位元）"></el-table-column>
                            <el-table-column prop="link_divide_price" label="佣金（单位元）"></el-table-column>
                        </el-table>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="海报名称" prop="title">
                            <el-input style="width:50%" v-model="posterForm.title" placeholder="请输入名称" size="small" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-dialog :visible.sync="popuLinkOpen" width="1000px" append-to-body title="选择推广商品链接">
                <div class="table-wrap">
                    <el-table :data="tablePopuLinkData" v-loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all>
                        <el-table-column prop="name" label="商品名称"></el-table-column>
                        <el-table-column prop="img" label="缩略图">
                            <template slot-scope="scope">
                                <el-image :src="scope.row.img" fit="fill" style="width: 60px;height: 60px;"></el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="link_yard" label="唯一识别码"></el-table-column>
                        <el-table-column prop="goods_quantity" label="商品数量"></el-table-column>
                        <el-table-column prop="sold_quantity" label="已售数量"></el-table-column>
                        <el-table-column prop="link_price" label="商品价格（单位元）"></el-table-column>
                        <el-table-column prop="link_divide_price" label="佣金（单位元）"></el-table-column>
                        <el-table-column prop="link_level" label="级别">
                            <template slot-scope="scope">
                                <span v-if="scope.row.link_level == 1">一级</span>
                                <span v-else>二级</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="user_name" label="创建人"></el-table-column>
                        <el-table-column prop="add_time" label="创建时间"></el-table-column>
                        <el-table-column prop="id" label="操作">
                            <template slot-scope="scope">
                                <el-button v-if="selectPopuItem.length == 0 || selectPopuItem[0].id != scope.row.id" type="text" size="mini" icon="fa fa-pencil" @click="selectPopu(scope.row)">选择</el-button>
                                <el-button v-if="selectPopuItem.length > 0 && selectPopuItem[0].id == scope.row.id" type="text" size="mini" icon="fa fa-pencil" @click="cancelSelect(scope.row)">取消选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block">
                        <el-pagination @size-change="handlePopuSizeChange" @current-change="handlePopuCurrentChange"
                                       :current-page="popuForm.pagePopuNumber" :page-sizes="[10, 50, 100, 200]"
                                       :page-size="popuForm.pagePopuSize"
                                       background layout="total, sizes, prev, pager, next, jumper"
                                       :total="popuForm.popuTotal">
                        </el-pagination>
                    </div>
                </div>
            </el-dialog>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleClose" size="small">取 消</el-button>
                <el-button type="primary" @click="!posterForm.id ? submitForm('posterForm') : subEditForm('posterForm')"
                           size="small">确 定</el-button>
            </div>
        </el-dialog>
        <select-posters :show="IsShowPicDig" @update="cleanDiaglog" :selectType="imgnum" @selectSure="selectImgs" :type="0"></select-posters>
    </div>
</template>

<script>
import {
    getPopuList,
    getPopuLinkList,
    createdPoster,
    delPoster,
    getPosterInfo,
    editePoster
} from "@/api/sell/posters/posters";

import Panle from '@/components/Panle';
import PersButton from '@/components/PersButton';
import {hasPermission, isShow} from '@/common/permission';
import {mapState} from "vuex";
import SelectPosters from "@/components/select-posters.vue";
import {checkPopuLink} from "@/api/sell/popu/popu";
import draggable from 'vuedraggable'

export default {
    name:'Examine',
    components: {
        SelectPosters,
        Panle,
        PersButton,
        draggable
    },
    computed:{
        ...mapState({
            userInfo: state => state.member.userInfo,
        }),
    },
    data() {
        return {
            loading:false,
            PosterOpen:false, //添加/编辑弹框是否显示
            IsShowPicDig: false, //选择模板弹框
            popuLinkOpen:false, //选择推广链接弹框
            currentPopuShow:false,
            form: {
                title:'',
                pagePostersSize: 10,
                pagePostersNumber: 1,
                postersTotal: 0,

            },
            posterForm:{},
            popuForm:{
                pagePopuSize: 10,
                pagePopuNumber: 1,
                popuTotal: 0,
            },
            tableData:[],
            posterData:[],
            tablePopuLinkData:[],
            selectPopuItem:[],
            imgnum: 1, //选择图片数量
            dialogImageUrl: '',
            dialogImageId:'',
            popuQrcode:'',// 二维码
            popuQrcodeBase64:'', //base64位二维码
            position:{
                x:0,
                y:0
            },

          qr_w:'',
          qr_h:'',
          dialogImage_w:720,
          bigImageAspectRatio: 2.55,
        }
    },
    created() {
        this.init(true);
    },
    methods: {
        hasPermission,
        isShow,
        init() {
            this.loading = true;
          getPopuList(this.form).then((res) => {
                this.tableData = res.data.data;
                this.form.postersTotal = res.data.total;
                this.loading = false;
            })
        },

        popuInit(){
            this.loading = true;
            this.popuForm.page = this.popuForm.pagePopuNumber
            this.popuForm.size = this.popuForm.pagePopuSize
            getPopuLinkList(this.popuForm).then((res) => {
                this.tablePopuLinkData = res.data.data;
                this.popuForm.popuTotal = res.data.total;
                this.popuLinkOpen = true;
                this.loading = false;
            })
        },

        //关闭弹框回调
        handleClose(){
            this.PosterOpen = false;
            this.dialogImageUrl = '';
            this.dialogImageId = '';
            this.selectPopuItem = [];
            this.posterForm = {};
            this.popuQrcode = '';
            this.position.x = '';
            this.position.y = '';
        },

        search: function () {
            this.loading = true;
            this.form.pagePostersSize = 10;
            this.form.pagePostersNumber = 1;
            this.init();
        },

        handlePostersSizeChange: function (e) {
            this.form.pagePostersSize = e;
            this.init();
        },

        handlePostersCurrentChange: function (e) {
            this.form.pagePostersNumber = e;
            this.init();
        },

        handlePopuSizeChange: function (e) {
            this.popuForm.pagePopuSize = e;
            this.popuInit();
        },

        handlePopuCurrentChange: function (e) {
            this.popuForm.pagePopuNumber = e;
            this.popuInit();
        },

        resetForm(formName) {
            this.form.title = '';
            this.init();
        },

        createdPoster:function (e){
            this.PosterOpen = true;
            this.currentPopuShow = false;
        },

        selectImgs: function (res) {
            this.IsShowPicDig = true;
            const dataObj = JSON.parse(res[0].pos);
            this.dialogImageUrl = res[0].urls;
            this.dialogImageId = res[0].id;
            this.position.x = dataObj.x;
            this.position.y = dataObj.y;
        },

        cleanDiaglog: function (shows) {
            this.IsShowPicDig = false;
        },

        openUploadDialBg: function () {
            this.IsShowPicDig = true;
        },

        selectPopuLink:function (){
            this.popuInit();
        },

        //选择链接
        selectPopu:function (e){
            this.loading = true;
            var param = {
                'id':e.id,
            }
            checkPopuLink(param).then((res) => {
                if(res.code == 200){
                    this.popuQrcodeBase64 = res.data.popu_link_qrcode;
                    this.convertBase64ToPng(res.data.popu_link_qrcode,pngData => {
                        this.popuQrcode = URL.createObjectURL(pngData);
                      this.qr_w = this.dialogImage_w / this.bigImageAspectRatio;
                      this.qr_h = this.qr_w;
                    })
                    this.loading = false;
                }
            })

            this.selectPopuItem = [e];
            this.popuLinkOpen = false;
            this.currentPopuShow = true;
        },
        //取消选择
        cancelSelect:function (e){
            this.selectPopuItem = [];
            this.currentPopuShow = false;
            this.popuLinkOpen = false;
        },

        //base64 to png
        convertBase64ToPng(base64Data, callback) {
            // 将base64字符串转换为Blob对象
            const byteCharacters = atob(base64Data.split(',')[1]);
            const arrayBuffer = new ArrayBuffer(byteCharacters.length);
            const uintArray = new Uint8Array(arrayBuffer);
            for (let i = 0; i < byteCharacters.length; i++) {
                uintArray[i] = byteCharacters.charCodeAt(i);
            }
            const blob = new Blob([uintArray], { type: 'image/jpeg' });
            callback(blob);
        },

        onEnd(event) {
            this.position.x = event.originalEvent.offsetX - 75
            this.position.y = event.originalEvent.offsetY - 75
        },

        //下载海报
        uploadPoster:function(data){
            const link = document.createElement("a");
            link.href = data.content; // 设置为图片的 URL
            link.download = data.title + ".jpg"; // 设置下载文件名
            link.click()
        },

        //删除海报
        delPoster:function(data){
            delPoster(data).then((res)=>{
                if(res.code==200){
                    this.msgSuccess(res.msg);
                    this.init();
                }else{
                    this.msgError(res.msg);
                }
            })
        },

        //编辑海报
        editPoster:function(data){
            getPosterInfo(data).then((res)=>{
                if(res.code==200){
                    this.PosterOpen = true;
                    this.posterForm = res.data.poster;
                    this.dialogImageUrl = res.data.poster.basemap;
                    this.position.x = res.data.poster.qr_code_position.x;
                    this.position.y = res.data.poster.qr_code_position.y;
                    this.selectPopuItem = [res.data.popu_link];
                    this.dialogImageId = res.data.poster.posters_template_id;
                    this.currentPopuShow = true;
                    var param = {
                        'id':this.selectPopuItem[0].id,
                    }
                    checkPopuLink(param).then((res) => {
                        if(res.code == 200){
                            this.popuQrcodeBase64 = res.data.popu_link_qrcode;
                            this.convertBase64ToPng(res.data.popu_link_qrcode,pngData => {
                                this.popuQrcode = URL.createObjectURL(pngData);
                            })
                        }
                    })
                }else{
                    this.msgError(res.msg);
                }
            })
        },

        //创建提交
        submitForm:function(data){
            this.$refs[data].validate((valid) => {
                if (valid) {
                    this.posterForm['popu_link_id'] = this.selectPopuItem[0].id;
                    this.posterForm['goods_id'] = this.selectPopuItem[0].goods_id;
                    this.posterForm['link_yard'] = this.selectPopuItem[0].link_yard;
                    this.posterForm['basemap'] = this.dialogImageUrl;
                    this.posterForm['popuQrcode'] = this.popuQrcodeBase64;
                    this.posterForm['x'] = this.position.x;
                    this.posterForm['y'] = this.position.y;
                    this.posterForm['posters_template_id'] = this.dialogImageId;
                    this.posterForm['type'] = 1;
                    this.posterForm['qr_w'] = Math.round(this.qr_w);
                    this.posterForm['qr_h'] = Math.round(this.qr_h);
                    createdPoster(this.posterForm).then((res)=>{
                        if(res.code==200){
                            this.msgSuccess(res.msg);
                            this.PosterOpen=false;
                            this.dialogImageUrl = '';
                            this.dialogImageId = '';
                            this.selectPopuItem = [];
                            this.posterForm.title = '';
                            this.popuQrcode = '';
                            this.position.x = '';
                            this.position.y = '';
                            this.init();
                        }else{
                            this.msgError(res.msg);
                        }
                    })
                }else{
                    return false;
                }
            })
        },

        //编辑提交
        subEditForm:function(data){
            this.$refs[data].validate((valid) => {
                if (valid) {
                    this.posterForm['link_yard'] = this.selectPopuItem[0].link_yard;
                    this.posterForm['posters_template_id'] = this.dialogImageId;
                    this.posterForm['x'] = this.position.x;
                    this.posterForm['y'] = this.position.y;
                    this.posterForm['goods_id'] = this.selectPopuItem[0].goods_id;
                    this.posterForm['popuQrcode'] = this.popuQrcodeBase64;
                    this.posterForm['basemap'] = this.dialogImageUrl;
                    editePoster(this.posterForm).then((res)=>{
                        if(res.code==200){
                            this.msgSuccess(res.msg);
                            this.PosterOpen=false;
                            this.dialogImageUrl = '';
                            this.dialogImageId = '';
                            this.selectPopuItem = [];
                            this.posterForm.title = '';
                            this.popuQrcode = '';
                            this.position.x = '';
                            this.position.y = '';
                            this.init();
                        }else{
                            this.msgError(res.msg);
                        }
                    })
                }else{
                    return false;
                }
            })
        },
    }
}

</script>

<style lang="scss" scoped>
.demo-form-inline {
    margin: 20px;

    .el-form-item {
        margin-bottom: 0;
    }
}
.el-form--inline .el-form-item {
    display: inline-block;
    vertical-align: top;
}

.orderListRuleForm .el-form-item {
    margin-bottom: 0;
}

.search-content {
    width: 100%;
    margin: 20px;
}

.create_poster{
    margin-top: 7px;
    float: right;
}

.w50{
    width: 50px !important;
}
.w60{
    width: 60px !important;
}
.w260{
    width: 260px !important;
}
.mr20{
    margin-right: 20px;
}
.qrCode{
    position: absolute;
}
.dragArea{
    position: absolute;
}
.uploadcol{
    width:100%;
    height: 100%;
    position: relative;
}
</style>
